from django.core.files.storage import FileSystemStorage
from django.conf import settings
import os
import time
from django_oss_storage.backends import OssMediaStorage

class HybridStorage(FileSystemStorage):
    """
    混合存储策略：
    1. 新文件先存储在本地
    2. 通过定时任务将过期文件上传到OSS
    3. 读取时优先查找本地，不存在则尝试从OSS获取
    """
    def __init__(self):
        super().__init__(location=settings.MEDIA_ROOT, base_url=settings.MEDIA_URL)
        self.oss_storage = OssMediaStorage()

    def created_time(self, name):
        """获取文件创建时间"""
        return os.path.getctime(self.path(name))

    def exists_oss(self, name):
        """检查OSS是否存在文件"""
        return self.oss_storage.exists(name)

    def save(self, name, content, max_length=None):
        """保存到本地时记录时间戳"""
        name = super().save(name, content, max_length)
        # 添加创建时间元数据
        os.utime(self.path(name), (time.time(), time.time()))
        return name

    def open(self, name, mode='rb'):
        """优先打开本地文件，不存在则尝试从OSS获取"""
        if not super().exists(name):
            if self.exists_oss(name):
                content = self.oss_storage.open(name)
                self.save(name, content)
        return super().open(name, mode)